// 获取日期事件数据

import {
  getStorage,
  formatDate,
} from "./common.js";

// 常量
export const dataKey = "dc-data";
export const configKey = "dc-config";

/**
 * @description 获取日期事件数据，系统自带+用户
 * @author start2004
 * @since 2025-08-12
 *
 * @returns {array} 日期事件数据
 */
export async function getAllDates(){
  let dates = [];

  /**
   * @since 2025-08-13 用户的日期事件，object
   */
  let userDates = await getUserDates();
  for(const k in userDates){
    dates.push(userDates[k]);
  }

  /**
   * @since 2025-08-14 获取用户配置
   */
  let userConfig = await getUserConfig();
  if(userConfig.holiday){
    /**
     * @since 2025-08-14 合并节假日数据
     * @since 2025-08-13 获取系统的日期事件，array
     */
    let systemDates = await getSystemDates();
    dates.push(...systemDates);
  } else {}

  /**
   * @return
   */
  return dates;
}

/**
 * @description 获取用户配置信息
 * @author start2004
 * @since 2025-08-14
 *
 * @returns {object} 用户配置信息
 */
export async function getUserConfig(){
  let userConfig = await getStorage(configKey);
  if(userConfig === undefined){
    userConfig = {
      holiday: true,
    }
  } else {}

  return userConfig;
}

/**
 * @description 获取系统的日期事件数据
 * @author start2004
 * @since 2025-08-13
 *
 * @returns {array} 日期事件数据
 */
export async function getSystemDates(){
  let dates = [];

  /**
   * @since 2025-08-12 读取节假日数据，data/zh_CN.json文件
   */
  let url = chrome.runtime.getURL('../data/holidays/'+ chrome.i18n.getMessage("language") +'.json');
  let response = await fetch(url);
  let holidays = await response.json();
  for(const k in holidays){
    dates.push({
      "title": holidays[k],
      "date": k,
      "level": "null"
    });
  }

  /**
   * @return
   */
  return dates;
}

/**
 * @description 获取用户的日期事件数据，用于用户的日期事件数据编辑
 * @author start2004
 * @since 2025-08-13
 *
 * @returns {object} 日期事件数据
 */
export async function getUserDates(){
  /**
   * @since 2025-08-12 用户自定义的日期事件
   */
  let userObject = await getStorage(dataKey);
  if(userObject === undefined){
    userObject = {};
  } else {}

  /**
   * @return
   */
  return userObject;
}

/**
 * @description 获取今天到期的任务
 * @author start2004
 * @since 2025-09-25
 *
 * @returns {array} 返回今天到期的任务
 */
export async function getDueTasks(){
  /**
   * @since 2025-09-26 获取所有任务
   */
  let tasks = await getAllDates();

  /**
   * @since 2025-09-26 过滤当天数据
   */
  let dueTasks = new Array();
  const today = formatDate(new Date(), "zh_CN");
  tasks.forEach(item => {
    if(item.date == today) dueTasks.push(item);
  });

  return dueTasks;
}